package com.csmarket.csmarketbackend.controller;

import com.csmarket.csmarketbackend.common.Result;
import com.csmarket.csmarketbackend.pojo.Users;
import com.csmarket.csmarketbackend.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.csmarket.csmarketbackend.service.UserService;

import java.util.HashMap;
import java.util.Map;

@RestController
public class AuthController {
    @Autowired
    private UserService userService;
    @Autowired
    private JwtUtils jwtUtils;
    @PostMapping("/login")
    public Result<Map<String, Object>> login(@RequestParam String username, @RequestParam String password) {

        if (userService.authenticate(username, password)) {
            String token = jwtUtils.generateToken(username);
            // 获取用户信息
            Users user = userService.getUserByName(username);

            Map<String, Object> response = new HashMap<>();
            response.put("token", token);
            response.put("username", username);
            response.put("role", user.getRole());

            return Result.success(response);
        } else {
            return Result.error("用户名或密码错误");
        }
    }

    @PostMapping("/register")
    public Result<Map<String, Object>> register(@RequestParam String username, @RequestParam String password) {
        Map<String, Object> response = new HashMap<>();

        if (userService.registerUser(username, password)) {
            response.put("success", true);
            response.put("message", "注册成功");
            return Result.success(response);
        } else {
            return Result.error("注册失败，用户名可能已存在");
        }
    }
}
